package service

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"log"
	"math/rand"
	"srv/basic/config"
	__ "srv/basic/proto"
	"srv/handler/models"
	"srv/pkg"
	"srv/untils"
	"strconv"
	"time"
)

type Server struct {
	__.UnimplementedTaxiServer
}

// SendSms
func (s *Server) SendSms(_ context.Context, req *__.SendSmsReq) (*__.SendSmsResp, error) {
	code := rand.Intn(9000) + 1000
	t := time.Now().Add(-time.Minute * 1)                               //一分钟前的时间
	formattedTTime := t.Format("2006-01-02 15:04:05")                   //转换成Time.time
	count, _ := config.Rdb.Get(config.CTX, "sendSms:"+req.Mobile).Int() //获取发送次数
	if formattedTTime < strconv.Itoa(60) {
		if count == 3 {
			return nil, errors.New("一分钟之内只能发送三次验证码")
		}
	}

	err, _ := pkg.SendSms(req.Mobile, strconv.Itoa(code))
	if err != nil {
		return nil, nil
	}
	config.Rdb.Set(config.CTX, "sendSms:"+req.Mobile, code, time.Minute*15)
	config.Rdb.Expire(config.CTX, "sendSms:"+req.Mobile, time.Minute*1) //一分钟的过期时间
	config.Rdb.Incr(config.CTX, "sendSms:"+req.Mobile)                  // 记录发送次数
	return &__.SendSmsResp{}, nil
}

func (s *Server) UserRegister(_ context.Context, in *__.UserRegisterReq) (*__.UserRegisterResp, error) {
	var user models.User
	user.Mobile = in.Mobile

	err := user.GetUserInfo()
	if err != nil {
		return nil, err
	}
	if user.ID != 0 {
		return nil, errors.New("当前用户已注册")
	}

	user.NickName = in.NickName
	user.Password = pkg.MD5(in.Password)
	user.UType = in.UType
	sendSmsCode := config.Rdb.Get(config.CTX, "sendSms:"+user.Mobile).Val()
	if sendSmsCode != in.Code {
		return nil, errors.New("验证码输入错误")
	}
	err = user.AddUser()
	if err != nil {
		return nil, err
	}

	return &__.UserRegisterResp{
		Id: int64(user.ID),
	}, nil
}

func (s *Server) UpdateUserType(_ context.Context, in *__.UpdateUserTypeReq) (*__.UpdateUserTypeResp, error) {
	var user models.User
	user.ID = uint(in.Id)
	user.UType = in.UType
	err := user.UpdateUserType()
	if err != nil {
		return nil, err
	}
	return &__.UpdateUserTypeResp{
		Id: int64(user.ID),
	}, nil
}

func (s *Server) DriverAuthentication(_ context.Context, in *__.DriverAuthenticationReq) (*__.DriverAuthenticationResp, error) {
	var driver models.DriverInfo
	driver.RealName = in.RealName
	driver.IdCard = in.IdCard
	driver.LicenseUrl = in.LicenseUrl
	driver.LicenseNumber = in.LicenseNumber

	if len(in.IdCard) != 18 {
		driver.Status = 3
		return nil, errors.New("身份证号码长度错误")
	}
	err := driver.GetDriverInfoByIdLicenseNumber()
	if err != nil {
		return nil, errors.New("当前车牌号已认证")
	} else {
		log.Panicln("审核通过")
	}

	return &__.DriverAuthenticationResp{}, nil
}

func (s *Server) DriverExamine(_ context.Context, in *__.DriverExamineReq) (*__.DriverExamineResp, error) {
	var driver models.DriverInfo
	driver.RealName = in.RealName
	driver.IdCard = in.IdCard
	result := pkg.RealnameAuth(in.RealName, in.IdCard)
	if !result {
		return nil, errors.New("当前司机未认证")
	}
	return &__.DriverExamineResp{
		Id: int64(driver.ID),
	}, nil
}

func (s *Server) AddCar(_ context.Context, req *__.AddCarReq) (*__.AddCarResp, error) {
	var user models.User
	user.ID = uint(req.UserId)
	if err := user.GetUserById(); err != nil {
		return nil, err
	}
	if user.ID == 0 {
		return nil, errors.New("该用户不存在")
	}
	if user.UType != 2 {
		return nil, errors.New("不是司机权限")
	}
	car := models.Car{
		UserId:  int(user.ID),
		Brand:   req.Brand,
		Color:   req.Color,
		Seats:   req.Seats,
		CType:   req.CType,
		License: req.License,
	}
	if err := car.Create(); err != nil {
		return nil, err
	}
	return &__.AddCarResp{
		CarId: int64(car.ID),
	}, nil
}

func (s *Server) GetCarList(_ context.Context, in *__.GetCarTypeListReq) (*__.GetCarTypeListResp, error) {
	var car models.Car
	list, err := car.GetCarTypeList()
	if err != nil {
		return nil, err
	}

	var carTypeList []*__.CarTypeList
	for _, c := range list {
		carTypeList = append(carTypeList, &__.CarTypeList{
			CarType: c,
		})
	}
	return &__.GetCarTypeListResp{
		CarTypeList: carTypeList,
	}, nil
}
func (s *Server) CreateOrder(_ context.Context, in *__.OrderAddReq) (*__.OrderAddResp, error) {
	var order models.Order
	num := rand.Intn(100)
	order.UserId = int64(in.UserId)

	config.Rdb.Set(config.CTX, "price:", num*2+models.ModelPrice(in.Model), time.Minute*15)

	price := config.Rdb.Get(config.CTX, "price:").Val()

	order.Num = uuid.NewString()
	order.Origin = in.Origin
	order.End = in.End
	order.Model = in.Model
	order.Kilometers = int64(num)
	order.Price, _ = strconv.ParseFloat(price, 64)
	order.State = 1

	err := order.OrderAdd()
	if err != nil {
		return nil, fmt.Errorf("创建订单失败")
	}

	pkg.EsAdd()
	return &__.OrderAddResp{
		Id: uint64(order.Id),
	}, nil
}

func (s *Server) DriverRejectOrder(_ context.Context, req *__.DriverRejectOrderReq) (*__.DriverRejectOrderResp, error) {
	var order models.Order
	if err := order.GetOrderId(int(req.OrderId)); err != nil {
		return nil, err
	}
	if order.Id == 0 {
		return nil, errors.New("该订单不存在")
	}
	if order.DriverId != req.DriverId {
		return nil, errors.New("该订单不是您的")
	}

	if err := order.OrderUpdate(int(order.Id)); err != nil {
		return nil, err
	}

	return &__.DriverRejectOrderResp{
		Id:    order.Id,
		State: order.State,
	}, nil
}

func (s *Server) ConfirmPassenger(_ context.Context, req *__.ConfirmPassengerReq) (*__.ConfirmPassengerResp, error) {

	var order models.Order
	if err := order.GetOrderId(int(req.OrderId)); err != nil {
		return nil, err
	}
	if order.Id == 0 {
		return nil, errors.New("该订单不存在")
	}
	if order.DriverId != req.DriverId {
		return nil, errors.New("该订单不是您的")
	}
	var user models.User
	if err := user.GetUserById(); err != nil {
		return nil, err
	}
	if user.ID == 0 {
		return nil, errors.New("该用户不存在")
	}
	if user.Mobile[7:11] != req.Mobile {
		return nil, errors.New("手机号错误")
	}
	order.State = 2
	if err := order.OrderUpdate(int(order.Id)); err != nil {
		return nil, err
	}
	return &__.ConfirmPassengerResp{
		Id: order.Id,
	}, nil
}

func (s *Server) OrderUpdateFinish(_ context.Context, in *__.OrderUpdateFinishReq) (*__.OrderUpdateFinishResp, error) {
	var order models.Order
	if err := order.GetOrderId(int(in.Id)); err != nil {
		return nil, err
	}
	if order.Id == 0 {
		return nil, errors.New("当前订单不存在")
	}
	order.State = 3
	if err := order.OrderUpdateFinish(); err != nil {
		return nil, err
	}

	return &__.OrderUpdateFinishResp{
		Id: uint64(order.Id),
	}, nil
}

func (s *Server) PassengerPay(_ context.Context, req *__.PassengerPayReq) (*__.PassengerPayResp, error) {
	var order models.Order

	if err := order.GetOrderId(int(req.OrderId)); err != nil {
		return nil, err
	}
	if order.Id == 0 {
		return nil, errors.New("当前订单不存在")
	}

	if order.State == 2 {
		return nil, errors.New("该订单已支付")
	}
	alipay := untils.Pay{}
	money := fmt.Sprintf("%.2f", order.Price)
	return &__.PassengerPayResp{
		PayUrl: alipay.Alipay(order.Origin, money),
	}, nil
}

func (s *Server) OrderUserList(_ context.Context, in *__.OrderUserListReq) (*__.OrderUserListResp, error) {
	var order models.Order
	var orderList []*__.OrderUserList
	order.State = int64(in.State)
	list, err := order.OrderUserList()
	if err != nil {
		return nil, err
	}
	for _, o := range list {
		orderList = append(orderList, &__.OrderUserList{
			Id:         o.Id,
			DriverId:   o.DriverId,
			Num:        o.Num,
			Origin:     o.Origin,
			End:        o.End,
			Model:      o.Model,
			Kilometers: o.Kilometers,
			Price:      float32(o.Price),
		})
	}

	return &__.OrderUserListResp{
		List: orderList,
	}, nil
}
